<?php

class ImageEditor {
	const TYPE_PNG = 0;
	const TYPE_JPEG = 1;
	const TYPE_GIF = 2;
	
	const TYPE_UNKNOWN = -1;

	public static function resizeToWidth($adres, $width, $type) {
		list($_width, $_height) = getimagesize($adres);
		$new_height = $_height * $width/$_width;
		$new_width = $width;	
		return self::resize($adres, $new_width, $new_height, $_width, $_height, $type);
	}

	public static function resizeToHeight($adres, $height, $type) {
		list($_width, $_height) = getimagesize($adres);
		$new_width = $_width * $height/$_height;
		$new_height = $height;	
		return self::resize($adres, $new_width, $new_height, $_width, $_height, $type);
	}
	
	public static function resize($adres, $new_width, $new_height, $old_width, $old_height, $type) { 
		// Resample
		$image_p = imagecreatetruecolor($new_width, $new_height);
		switch($type) {
			case ImageEditor::TYPE_PNG:
				$image = imagecreatefrompng($adres); //(($type == true)?imagecreatefrompng($adres):imagecreatefromjpeg($adres));
				break;
			case ImageEditor::TYPE_JPEG:
				$image = imagecreatefromjpeg($adres);
				break;
			case ImageEditor::TYPE_GIF:
				$image = imagecreatefromgif($adres);
				break;
		}
		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
		return $image_p;
	}
	
	public static function getType($adress) {
		$info = pathinfo($adress);
		switch(strtolower($info['extension'])) {
			case 'png':
				return ImageEditor::TYPE_PNG;
			case 'jpg':
			case 'jpeg':
				return ImageEditor::TYPE_JPEG;
			case 'gif':
				return ImageEditor::TYPE_GIF;
		}
		return ImageEditor::TYPE_UNKNOWN;
	}
	
	//usage: list($width, $height) = ImageEditor::getSize($adress);
	public static function getSize($adress) {
		return getimagesize($adress);
	}
		
	public static function getWidth($adress) {
		list($width, $height) = ImageEditor::getSize($adress);
		return $width;
	}
	
	public static function getHeight($adress) {
		list($width, $height) = ImageEditor::getSize($adress);
		return $height;
	}
	
	public static function saveImage($image, $type, $fileName) {
		switch($type) {
			case ImageEditor::TYPE_PNG:
				imagepng($image, $fileName);
				break;
			case ImageEditor::TYPE_JPEG:
				imagejpeg($image, $fileName);
				break;
			case ImageEditor::TYPE_GIF:
				imagegif($image, $fileName);
				break;
		}
	}
	
	public static function getExtension($type) {
		switch($type) {
			case ImageEditor::TYPE_PNG:
				return 'png';
			case ImageEditor::TYPE_JPEG:
				return 'jpg';
			case ImageEditor::TYPE_GIF:
				return 'gif';
		}
		return null;
	}
}
